package com.example.qbb01;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * HTTP 工具类
 */
public class HttpUtils {

    /**
     * POST请求
     *
     * @param urlStr
     * @param paramsStr
     * @param callback
     */
    public static void doPost(String urlStr, String paramsStr, HttpCallback callback) {
        try {
            // 第一步 根据服务器请求地址，创建URL对象
            URL url = new URL(urlStr);
            // 第二步，通过url打开连接
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为 POST
            httpURLConnection.setRequestMethod("POST");
            // 设置请求头为可输出
            httpURLConnection.setDoOutput(true);

            // 获取输出流，用于发送请求数据
            OutputStream outputStream = httpURLConnection.getOutputStream();
            // 基于输出流构建 Writer
            OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            writer.write(paramsStr);
            writer.flush();
            writer.close();

            // 写完之后，需要看服务器是否正常接收到数据
            httpURLConnection.connect();
            // 获取服务器的响应码
            int responseCode = httpURLConnection.getResponseCode();
            // 根据响应码判断是否成功，200表示成功
            if (responseCode == 200) {
                // 连接成功，处理服务器响应数据
                InputStream inputStream = httpURLConnection.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String line;
                // 一次读一行数据
                StringBuffer stringBuffer = new StringBuffer();
                while ((line = bufferedReader.readLine()) != null) {
                    // 读到数据拼接到StringBuffer上
                    stringBuffer.append(line);
                }
                bufferedReader.close();
                Log.d("HTTP", stringBuffer.toString());
                callback.onHttpSucceed();
            } else {
                Log.d("HTTP", "请求失败，" + responseCode);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
